package org.example.auth.config.web;

import org.example.common.core.constants.CacheConstants;
import org.example.common.redis.utils.RedisUtils;
import org.springframework.security.oauth2.provider.AuthorizationRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@Controller
@SessionAttributes("authorizationRequest")
public class GrantController {

    static final String AUTHORIZATION_REQUEST_ATTR_NAME = "authorizationRequest";
    static final String ORIGINAL_AUTHORIZATION_REQUEST_ATTR_NAME = "org.springframework.security.oauth2.provider.endpoint.AuthorizationEndpoint.ORIGINAL_AUTHORIZATION_REQUEST";


    @RequestMapping("/oauth/confirm_access")
    public ModelAndView getAccessConfirmation(Map<String, Object> model, HttpServletRequest request) throws Exception {
        AuthorizationRequest authorizationRequest = (AuthorizationRequest) request.getAttribute("authorizationRequest");
        Map<String, Object> originalAuthorizationRequest = (Map<String, Object>) request.getAttribute(ORIGINAL_AUTHORIZATION_REQUEST_ATTR_NAME);
        ModelAndView view = new ModelAndView();
        view.setViewName("base-grant"); //自定义页面名字，resources\templates\base-grant.html
        view.addObject("clientId", authorizationRequest.getClientId());
        view.addObject("scopes",authorizationRequest.getScope());
        String key=String.format("%s:%s",CacheConstants.AUTHORIZATION_MODEL,authorizationRequest.getClientId());
        RedisUtils.setCacheMapValue(key,AUTHORIZATION_REQUEST_ATTR_NAME,authorizationRequest);
        RedisUtils.setCacheMapValue(key,ORIGINAL_AUTHORIZATION_REQUEST_ATTR_NAME,originalAuthorizationRequest);
        return view;
    }


    @GetMapping("/oauth/login")
    public ModelAndView loginPage(Model model,HttpServletRequest request){
        ModelAndView view = new ModelAndView();
        view.setViewName("base-login");
        view.addObject("errorMsg",request.getSession().getAttribute("errorMsg"));
        return view;
    }

    @RequestMapping("/oauth/error")
    public ModelAndView error(Map<String, Object> model, HttpServletRequest request) throws Exception {
        ModelAndView view = new ModelAndView();
        view.setViewName("base-error");
        return view;
    }
}
